package akka.scala.liuwei

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

case object PingMessage
case object PongMessage
case object StartMessage
case object StopMessage

/**
  * Created by liuwei on 2017/5/12.
  */
class Ping(pong:ActorRef) extends Actor {
  var count = 0
  def incrementAndPrint {count += 1; println(s"$count:ping")}

  def receive: Receive = {
    case StartMessage =>
      incrementAndPrint
      pong ! PongMessage
    case PingMessage =>
      incrementAndPrint
      if(count > 9) {
        sender ! StopMessage
        println("ping stopped")
        context.stop(self)
      }
      else
        sender ! PongMessage
    case _ => println("Ping got unexpected information")
  }


}

class Pong extends Actor {
  var count = 0
  def receive = {
    case StopMessage =>
      println("pong stopped")
      //context.stop方法来结束
      context.stop(self)
    case PongMessage =>
      count += 1
      println(s"$count:pong")
      sender ! PingMessage
    case _ => println("Pong got unexpected information")
  }
}

object PingPangTest extends App{
  val system = ActorSystem("PingPongTest")
  //创建Pong的actor实例（pongActor对象其实是ActorRef的实例）；
  val pongActor = system.actorOf(Props[Pong], name="pong")
 // Ping的actor实例，其构造函数接受ActorRef参数；
  val pingActor = system.actorOf(Props(new Ping(pongActor)),
    name = "ping")
  //通过给pingActor发送一个StartMessage消息来启动pingActor和pongActor的具体动作
  pingActor ! StartMessage
}
